package com.devunion.bogdan.persistence;

import java.io.Serializable;


/**
 * Base class for domain (bussiness) objects. Provides default implementation of
 * PersistentObject interface and consistent equals/hashCode methods based on object's
 * primary key.
 *
 * @author Viktar Liaskovich
 */
public abstract class BasePersistentObject implements Serializable {
    protected Serializable key;

    public BasePersistentObject() {}

    public BasePersistentObject(Serializable id) {
        this.key = id;
    }

    /**
     * Primary key.
     *
     * @return key
     */
    public Serializable getKey() {
        return key;
    }

    public void setKey(Serializable id) {
        this.key = id;
    }

    /**
     * 
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object other) {
        if ((other == null) || !this.getClass().isAssignableFrom(other.getClass())) {
            return false;
        }
        BasePersistentObject castOther = (BasePersistentObject) other;

        if (getKey() == null) {
            return super.equals(castOther);
        }

        return getKey().equals(castOther.getKey());
    }

    /**
     * 
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        if (getKey() == null) {
            return super.hashCode();
        }
        return getKey().hashCode();
    }

    /**
     * 
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return this.getClass().getName();
    }
}
